#include "EchoTask.h"
using namespace yazi::task;

#include "SocketHandler.h"
using namespace yazi::socket;

#include "Singleton.h"
#include "Logger.h"
using namespace yazi::utility;

#include <cerrno>
#include <cstring>


#define BUFSIZE 1024

EchoTask::EchoTask(Socket* socket) : Task(socket) {

}

EchoTask::~EchoTask(){

}

void EchoTask::run(){
    SocketHandler* sockethandler = Singleton<SocketHandler>::instance();
    Socket* socket = static_cast<Socket*>(m_data);
    char buf[BUFSIZE];
    memset(buf, 0, BUFSIZE);
    int len = socket->recv(buf, BUFSIZE);
    if(len == 0){
        error("socket closed by peer");
        sockethandler->remove(socket);
        return;
    }
    else if(len == -1 && errno == EAGAIN){
        error("socket recv len: %d, error msg: EAGAIN, errno: %d", len, errno);
        sockethandler->attach(socket);
        return;
    }
    else if(len == -1 && errno == EWOULDBLOCK){
        error("socket recv len: %d, error msg: EWOULDBLOCK, errno: %d", len, errno);
        sockethandler->attach(socket);
        return;
    }
    else if(len == -1 && errno == EINTR){
        error("socket recv len: %d, error msg: EINTR, errno: %d", len, errno);
        sockethandler->attach(socket);
        return;
    }
    else if(len == -1){
        error("socket recv len: %d, errno: %d", len, errno);
        sockethandler->remove(socket);
        return;
    }
    else{
        buf[len] = 0;
        socket->send(buf, len);
        info("echo task: %s", buf);
        sockethandler->attach(socket);
    }
}

void EchoTask::destroy(){
    debug("echo task destroy");
    delete this;
}